<template>
  <div class="login_module bgc1">
    <el-card class="form_module" style="max-width: 400px">
      <!-- 元服务SaaS平台 -->
      <div class="wfull flex justify_center mb22 font_size_22 font_weight_bold">
        {{ $t("login_title") }}
      </div>
      <el-tabs v-model="activeName" @tab-click="handleChangeTab" stretch>
        <!-- 密码登录表单 -->
        <el-tab-pane
          :label="$t('login_tab_password_login')"
          :name="TabsListEnum.Login"
        >
          <el-form
            :model="passwordForm"
            :rules="passwordLoginRules"
            label-width="auto"
            style="max-width: 600px"
            ref="passwordRuleFormRef"
          >
            <!-- 手机号/邮箱 -->
            <el-form-item class="mt22" prop="phoneNum">
              <div class="form_item wfull">
                <el-input
                  class="form_item_input"
                  v-model="passwordForm.phoneNum"
                  :placeholder="$t('login_phoneoremail_placeholder')"
                >
                  <template #prepend>
                    <div class="iconfont icon-yonghu"></div>
                  </template>
                </el-input>
              </div>
            </el-form-item>

            <!-- 密码 -->
            <el-form-item prop="password">
              <div class="form_item wfull">
                <div class="form_item_input">
                  <passwordInput v-model="passwordForm.password" ></passwordInput>
                </div>
              </div>
            </el-form-item>

            <!-- 登陆按钮 -->
            <el-form-item>
              <div class="wfull form_item">
                <el-button
                  class="wfull form_item_input"
                  type="primary"
                  :loading="loginLoading"
                  @click="hangleLogin(passwordRuleFormRef)"
                  >{{ $t("login_login_btn") }}</el-button
                >
              </div>
            </el-form-item>
            <!-- 阅读协议、忘记密码操作 -->
            <el-form-item prop="isChecked">
              <div class="wfull flex justify_between form_item">
                <el-checkbox-group v-model="passwordForm.isChecked">
                  <el-checkbox value="1" name="isChecked">
                    {{ $t("login_readTheAgreement") }}
                  </el-checkbox>
                </el-checkbox-group>
                <span class="pointer">{{
                  $t("login_forgotPassword_btn")
                }}</span>
              </div>
            </el-form-item>
            <!-- 在线客服、立即注册 -->
            <el-form-item>
              <div class="wfull flex justify_end">
                <span class="pointer">{{ $t("login_onlineService_btn") }}</span>
                <span class="pointer ml10" @click="handleRegister">{{
                  $t("login_registerNow_btn")
                }}</span>
              </div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <!-- 短信登陆表单 -->
        <el-tab-pane
          :label="$t('login_tab_text_message_login')"
          :name="TabsListEnum.Msg"
        >
          <el-form
            :model="msgForm"
            :rules="msgLoginRoule"
            label-width="auto"
            style="max-width: 600px"
            ref="msgdRuleFormRef"
          >
            <!-- 手机号 -->
            <el-form-item class="mt22" prop="phoneNum">
              <div class="form_item wfull">
                <el-input
                  class="form_item_input"
                  v-model="msgForm.phoneNum"
                  :placeholder="$t('login_phoneoremail_placeholder')"
                >
                  <template #prepend>
                    <div class="iconfont icon-yonghu"></div>
                  </template>
                </el-input>
              </div>
            </el-form-item>
            <!-- 短信验证码 -->
            <el-form-item prop="mgs">
              <div class="form_item wfull flex">
                <div class="flex4">
                  <el-input
                    class="form_item_input"
                    v-model="msgForm.mgs"
                    :placeholder="$t('login_msg__placeholder')"
                  >
                    <template #prepend>
                      <div class="iconfont icon-mima"></div>
                    </template>
                  </el-input>
                </div>
                <div>
                  <el-button :disabled="msgCountdownInfo.isDisabled" class="form_item_input" @click="getMsg">{{ msgCountdownInfo.buttonName }}</el-button>
                </div>
              </div>
            </el-form-item>
            <!-- 登陆按钮 -->
            <el-form-item>
              <div class="wfull form_item">
                <el-button
                  class="wfull form_item_input"
                  type="primary"
                  :loading="loginLoading"
                  @click="hangleLogin(msgdRuleFormRef)"
                  >{{ $t("login_login_btn") }}</el-button
                >
              </div>
            </el-form-item>
            <!-- 阅读协议、忘记密码操作 -->
            <el-form-item prop="isChecked">
              <div class="wfull flex justify_between form_item">
                <el-checkbox-group v-model="msgForm.isChecked">
                  <el-checkbox value="1" name="isChecked">
                    {{ $t("login_readTheAgreement") }}
                  </el-checkbox>
                </el-checkbox-group>
                <span class="pointer">{{
                  $t("login_forgotPassword_btn")
                }}</span>
              </div>
            </el-form-item>
            <!-- 在线客服、立即注册 -->
            <el-form-item>
              <div class="wfull flex justify_end">
                <span class="pointer">{{ $t("login_onlineService_btn") }}</span>
                <span class="pointer ml10" @click="handleRegister">{{
                  $t("login_registerNow_btn")
                }}</span>
              </div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <div class="bottom_tips font_size_12">
      {{ $t("register_form_register_bottom_tip_info") }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive,onMounted,watch } from "vue";
import type { TabsPaneContext, FormInstance, FormRules } from "element-plus";
import {
  TabsListEnum,
  PasswordRouleForm,
  PasswordRouleFormData,
  MsgRouleForm,
  MsgRouleFormData,
  countdownData
} from "../../viewModel/loginViewModel";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";

import {login} from "../../service/login/login"

import passwordInput from "@/components/passwordInput/passwordInput.vue"

const { t } = useI18n();

const router = useRouter();
const activeName = ref(TabsListEnum.Login);

// 登录按钮loading
let loginLoading = ref<boolean>(false);

// 定义密码登录表单校验规则
const passwordLoginRules = reactive<FormRules<PasswordRouleForm>>(
  PasswordRouleFormData
);
const passwordRuleFormRef = ref<FormInstance>();
// 定义密码登陆表单数据
const passwordForm = reactive<PasswordRouleForm>({
  phoneNum: "",
  password: "",
  isChecked: [],
});

// 定义短信登录表单校验规则
const msgLoginRoule = reactive<FormRules<MsgRouleForm>>(MsgRouleFormData);
const msgdRuleFormRef = ref<FormInstance>();
// 定义短信登陆表单数据
const msgForm = reactive<MsgRouleForm>({
  phoneNum: "",
  mgs: "",
  isChecked: [],
});

// 切换tab事件
const handleChangeTab = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event);
};


// 倒计时信息
let msgCountdownInfo = ref(countdownData);

// 定义倒计时函数
const getMsg = () => {

  msgCountdownInfo.value.isDisabled = true;
  // 开始倒计时
  let interval = window.setInterval(function () {
    msgCountdownInfo.value.buttonName = `${msgCountdownInfo.value.second}${t("login_form_login_msg_reacquired")}`;
    msgCountdownInfo.value.second = msgCountdownInfo.value.second - 1;
    if (msgCountdownInfo.value.second <= 0) {
      msgCountdownInfo.value.buttonName = t("login_getSms_btn");
      msgCountdownInfo.value.second = 60;
      msgCountdownInfo.value.isDisabled = false;
      window.clearInterval(interval);
    }
  }, 1000); // 一秒执行一次
};

onMounted(() => {
  let localCountdownInfo = JSON.parse(
    localStorage.getItem("msgCountdownInfo") as string
  );
  if (localCountdownInfo) {
    msgCountdownInfo.value = localCountdownInfo;
    if (msgCountdownInfo.value.second !== 60) {
      getMsg();
    }
  }
});

// 登录事件（密码登录、短信登录）
const hangleLogin = (formEl: FormInstance | undefined) => {
  
  if (!formEl) {
    return;
  }
  formEl.validate((valid,fields) => {
    if (valid) {
      loginLoading.value = true;
      login().then( async(res) => {
        console.log(res);
        localStorage.setItem('isLoggedIn', 'true'); // 如果登陆成功，更新登陆状态
        // console.log("dynamicRoutes =>",dynamicRoutes);
        
    // localStorage.setItem('dynamicRoutes', JSON.stringify(dynamicRoutes));
        loginLoading.value = false;
          router.push({
          path: "/baseLayout/home"
        })
      }).catch(err => {
        console.log(err);
        
      })
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 点击 立即注册 事件
const handleRegister = () => {
  router.push({
    path: "/register",
  });
};

// 监听对象，数据是否发生变化，改变就进行重新保存
watch(
  msgCountdownInfo,
  (newVal) => {
    let JSONSTR = JSON.stringify(newVal);
    localStorage.setItem("msgCountdownInfo", JSONSTR);
  },
  {
    deep: true, // 深度监听
  }
);
</script>
<style scoped>
.login_module {
  position: relative;
  height: 100vh;
  width: 100%;
}
.bottom_tips {
  position: absolute;
  width: 100%;
  bottom: 30px;
  text-align: center;
  color: #ffffff;
}
.form_module {
  position: fixed;
  min-width: 400px;
  top: 50%;
  left: 70%;
  transform: translate(0, -50%);
}
.form_item {
  height: 40px;
  line-height: 40px;
}
.form_item_input {
  height: 40px;
}
</style>
